<?php

/*
 * Yanis Framework, Yet ANother Internet Service for web and mobile technologists
 * @copyright Copyright (C) 2011 ch@rlesen. All rights reserved.
 * @license GNU/GPL
 * @author Charles EDOU NZE <charles at charlesen.fr>
 */

/**
 * Class Template
 *
 */
class Template {

    /**
     * @var Object The Registry object 
     */
    private $registry;

    /**
     * @var Object Template 
     */
    private $_page;

    /**
     * Include the page class, and build a page object to manage the content
     * and structure of the page
     * @param Registry $registry 
     */
    public function __construct(Registry $registry) {
        $this->registry = $registry;
        include YANIS_PATH . 'libraries/yanis/registry/page.php';
        $this->_page = new Page($this->registry);
    }

    /**
     * @param Object $newpage 
     */
    public function setPage($newpage) {
        $this->_page = $newpage;
    }

    /**
     * @return Object Page 
     */
    public function getPage() {
        return $this->_page;
    }

    /**
     * Build the Main view
     */
    public function render() {
        define('YANIS_BASENAME', $this->_page->getBaseName());
        $content = "";
        $contentUrl = $this->_page->getUrlPath('page');

        if ($contentUrl !== '' && file_exists($contentUrl) == true) {
            $content .= file_get_contents($contentUrl);
            $this->_page->setContent($content);

            // Write the base tag in the script
            if (strpos($content, '<base href') === false) {
                $this->_page->setContent(str_replace('<head>', '<head>' . "\n\t" . '<base href="' . YANIS_BASENAME . '" />', $this->_page->getContent()));
            }
            file_put_contents($contentUrl, $this->_page->getContent());

            include_once $contentUrl;
            print $this->_page->getGenerator();// Print the Framework generator
        } else {
            // Error 404
            header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
            include_once YANIS_PATH . 'system/404.php';
        }
    }

}

?>
